import React, { useEffect, useState } from "react";
import { wjlgetshiti, wjladdRequest } from "../axiosAPI/wjl";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Button, Modal } from "antd";
import { Toast } from "antd-mobile";
import Countdown from "./Count"; // Timer component
import Face from "./Face"; // Face verification component
import Watermark from "./Watermark";
import './Wjlkaoshi.scss'; // 引入样式文件

export default function Wjlkaoshi() {
	let navigate = useNavigate();
	let clazz = sessionStorage.getItem("clazz");
	let startTime = sessionStorage.getItem("startTime");
	let [search] = useSearchParams();
	let paperid = search.get("paperid");
	let sid = search.get("sid");

	const [isModalOpen, setIsModalOpen] = useState(false);
	const [result, setResult] = useState({});
	const [questionsArr, setQuestionsArr] = useState([]);
	const [isOverlayVisible, setIsOverlayVisible] = useState(true);
	const [warningCount, setWarningCount] = useState(0);
	const [showWarningModal, setShowWarningModal] = useState(false);

	useEffect(() => {
		getShiti();
		window.addEventListener("fullscreenchange", handleFullscreenChange);

		return () => {
			window.removeEventListener("fullscreenchange", handleFullscreenChange);
		};
	}, []);
	
	const getShiti = async () => {
		let {
			data: { data, code },
		} = await wjlgetshiti({ paperid, sid });
		if (code === 200) {
			setQuestionsArr(data);
		}
	};

	const handleFullscreenChange = () => {
		if (!document.fullscreenElement) {
			handleWarning();
		}
	};

	const handleWarning = () => {
		setWarningCount((prevCount) => {
			const newCount = prevCount + 1;
			if (newCount > 3) {
				setTimeout(() => {
					handleSubmit();
				}, 0);
			} else {
				setShowWarningModal(true);
			}
			return newCount;
		});
	};

	const confirmFullscreen = () => {
		enterFullscreen();
		setShowWarningModal(false);
	};

	const handleAnswerChange = (questionId, optionId, isMultipleChoice) => {
		setResult((prevResult) => {
			const newResult = { ...prevResult };
			if (isMultipleChoice) {
				if (!newResult[questionId]) {
					newResult[questionId] = [];
				}
				if (newResult[questionId].includes(optionId)) {
					newResult[questionId] = newResult[questionId].filter((id) => id !== optionId);
				} else {
					newResult[questionId].push(optionId);
				}
			} else {
				newResult[questionId] = optionId;
			}
			return newResult;
		});
	};

	const handleTextareaChange = (questionId, value) => {
		setResult((prevResult) => ({
			...prevResult,
			[questionId]: value,
		}));
	};

	const handleSubmit = async () => {
		let {
			data: { code },
		} = await wjladdRequest({ result, sid, paperid, clazz, startTime });
		if (code === 200) {
			Toast.show({
				icon: "success",
				content: "提交成功，即将跳转登录",
			});
			setTimeout(() => {
				navigate("/wjllogin");
				sessionStorage.removeItem("token");
			}, 2000);
		}
		setIsModalOpen(false);
	};

	const showModal = () => {
		setIsModalOpen(true);
	};

	const handleOk = () => {
		handleSubmit();
	};

	const handleCancel = () => {
		setIsModalOpen(false);
	};

	const enterFullscreen = () => {
		if (!document.fullscreenElement) {
			if (document.documentElement.requestFullscreen) {
				document.documentElement.requestFullscreen();
			} else if (document.documentElement.mozRequestFullScreen) {
				document.documentElement.mozRequestFullScreen(); //火狐
			} else if (document.documentElement.webkitRequestFullscreen) {
				document.documentElement.webkitRequestFullscreen(); //苹果
			} else if (document.documentElement.msRequestFullscreen) {
				document.documentElement.msRequestFullscreen(); //IE
			}
			setIsOverlayVisible(false);
		}
	};

	const [isFullscreenLocked, setIsFullscreenLocked] = useState(true);

	return (
		<div id="Wjlkaoshi">
			<Watermark />
			<div className="boxleft">
				<p style={{ fontSize: "20px", textAlign: "center", marginTop: "20px" }}>距离考试结束还剩：</p>
				<Countdown />
				{isOverlayVisible && (
					<div className="fullscreen-overlay">
						<Face setIsFullscreenLocked={setIsFullscreenLocked} />
						{!document.fullscreenElement && (
							<Button onClick={enterFullscreen} type="primary" disabled={isFullscreenLocked}>
								进入全屏
							</Button>
						)}
					</div>
				)}
			</div>
			<div className="boxright">
				{isOverlayVisible ? (
					<p style={{ color: "red", fontSize: "50px", textAlign: "center", marginTop: "20%" }}>请进入全屏模式答题</p>
				) : (
					questionsArr.map((item) => {
						const isMultipleChoice = item.cate === 2;
						return (
							<div key={item._id} className={isMultipleChoice ? "duoxuan" : item.cate === 1 ? "danxuan" : item.cate === 3 ? "panduan" : "jianda"}>
								<p style={{color:'black'}}>{item.title}</p>
								{item.cate !== 4 ? (
									item.options.map((ele) => (
										<p key={ele._id}>
											{isMultipleChoice ? (
												<input type="checkbox" name={item._id} value={ele._id} onChange={() => handleAnswerChange(item._id, ele._id, true)} />
											) : (
												<input type="radio" name={item._id} value={ele._id} onChange={() => handleAnswerChange(item._id, ele._id, false)} />
											)}
											{ele.title}
										</p>
									))
								) : (
									<textarea onChange={(e) => handleTextareaChange(item._id, e.target.value)}></textarea>
								)}
							</div>
						);
					})
				)}
				{!isOverlayVisible && (
					<Button onClick={showModal} type="primary" disabled={isOverlayVisible}>
						提交答案
					</Button>
				)}
				<Modal title="确认提交" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText="确认提交" cancelText="取消">
					<p>您确定要提交答案吗？</p>
				</Modal>
	
				<Modal
					title="警告"
					open={showWarningModal}
					onOk={confirmFullscreen}
					footer={[
						<Button key="ok" type="primary" onClick={confirmFullscreen}>
							确认
						</Button>,
					]}
				>
					<p>请勿退出全屏模式！</p>
				</Modal>
			</div>
		</div>
	);
	
}
